<template>
	<view class="withdraw-cash-box">
		<view class="withdraw-cash-navbar">
			<image class="to-back" src="@/static/fanhui.png" alt="" @click="goBack" />
			<text>提现</text>
			<text class="to-right" @click="pushPage('/pages/transfer/index')">转账</text>
		</view>
		<view class="withdraw-cash-remarks">
			<text class="withdraw-cash-remarks-title">备注：提现以100的倍数进行提现</text>
		</view>
		<view class="balance-box">
			<view class="my-balance-head">
				我的余额（元）
			</view>
			<view class="my-balance-body">
				{{ setDecimalPoint(userInfo.balance) }}
			</view>
		</view>
		<view class="withdraw-cash-content">
			<view class="amount-withdrawn">
				提现金额
				<input class="amount-withdrawn-input" v-model="withdrawReceived" type="number">
				<view class="amount-withdrawn-title">
					提现额度：<text>{{ setDecimalPoint(userInfo.balance_yes) }}</text>元
				</view>
			</view>
			
			<view class="amount-withdrawn" v-if="withdrawReceived>=2000">
				真实姓名
				<input class="amount-withdrawn-input" v-model="real_name" type="text">
				<view class="amount-withdrawn-title">
					当提现超过2000时，请输入绑定该微信的真实姓名
				</view>
			</view>
				
				
			
			<view class="alipay-box" @click="authorizationAlipay">
			<view v-if="!userInfo.weixin_openid" class="alipay-box" @click.stop="authorizationWxpay">
				<image class="alipay-logo" mode="widthFix" src="@/static/wxpay.svg" alt="" />
				<text>请先绑定授权微信账户</text>
				<image class="alipay-icon" src="@/static/to-right.png" alt="" />
			</view>
			<view v-else class="alipay-box">
				<image class="alipay-logo" mode="widthFix" src="@/static/wxpay.svg" alt="" />
				<text>已绑定账户：{{ userInfo.weixin_nick_name }}</text>
				<image class="alipay-icon" src="@/static/to-right.png" alt="" />
			</view>
<!-- 			<view class="bank-card">
				<view class="card-box">
					<u-swipe-action class="card-list" v-for="item in bankCardList" :key="item.id" :show="item.show"
						:options="options" @content-click="selectCard(item.id)" @click="setSetting" @open="open(item.id)">
						<view class="item u-border-bottom">
							<view class="card-left">
								<view style="margin-bottom: 18rpx;" class="">
									{{ item.name }}
								</view>
								<view class="">
									<text style="margin-right: 30rpx;">{{ item.nickname }}</text>
									<text>{{ item.account }}</text>
								</view>
							</view>
							<view class="card-clean" @click.stop="cleanBankCard(item.id)">
								<image v-show="currentIndex === item.id" style="width: 50rpx;" src="@/static/select.png"
									mode="widthFix">
								</image> -->
								<!-- <image style="width: 50rpx;" src="@/static/ashbin.png" mode="widthFix"></image> -->
			<!-- 				</view>
						</view>
					</u-swipe-action>
				</view>
				<view class="add-card" @click="openAddBank">
					<image style="width: 60rpx; margin-right: 20rpx;" src="@/static/add.png" mode="widthFix"></image>
					<text>添加银行卡</text>
				</view>-->
			</view> 
			<text class="withdraw-cash-tip">提现T+1工作日到账,手续费{{ userInfo.free }}（千分比）</text>
			<view class="immediate-withdrawal" @click="toWithdrawApply">
				<text class="immediate-withdrawal-title">立即提现</text>
			</view>
			<view class="foot-record">
				<view class="withdraw-cash-record" @click="viewRecord">
					提现记录
				</view>
				<view class="reward-record" @click="toBalanceLog">
					奖励记录
				</view>
			</view>
		</view>
		<uni-popup ref="addBankPopup" type="center" @maskClick="maskClick">
			<view class="withdraw-alipay">
				<!-- Account -->
				<u-field label-width="160" :clearable="false" label="银行卡账号" v-model="form.account" placeholder="请输入银行卡账号" />
				<!-- Name -->
				<u-field label-width="160" :clearable="false" label="持卡人姓名" v-model="form.real_name" placeholder="请输入持卡人姓名" />
				<!-- Name -->
				<u-field label-width="160" :clearable="false" label="提现银行" v-model="form.bank" placeholder="请输入银行名称" />
				<!-- Remark -->
				<u-field label-width="160" :clearable="false" label="银行支行" v-model="form.subbank" placeholder="如：金湾支行" />
			</view>
			<view class="submit-btn" @click="submitAddBank">
				确定提交
			</view>
		</uni-popup>
			<u-popup v-model="showPassword" mode="center" width="600"  :closeable="true"  border-radius="20">
				<view class="password_box">
					<view class="title">
						请输入密码
					</view>
					<u-input class="input" v-model="password" type="password" :password-icon='false' />
					<view class="button" @click="onSubmit">
						确定
					</view>
				</view>
			</u-popup>
	</view>
</template>

<script>
	import * as authorizationApi from '@/api/authorization/index.js';
	import * as UserApi from '@/api/user';
	import * as withdrawApi from '@/api/withdrawCash/index.js';
	import * as Verify from '@/utils/verify';
	import {
		nextTick
	} from "vue";
	export default {
		data() {
			return {
				real_name:'',
				password:'',
				showPassword:false,
				userInfo: {},
				withdrawReceived: '',
				form: {},
				bankCardList: [],
				currentIndex: 0,
				slideIndex: 0,
				options: [{
						text: '编辑',
						style: {
							backgroundColor: '#007aff'
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				]
			}
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			// 获取页面数据
			// this.getPageData()
			// console.log(this.userInfo, 'userInfo');
			this.getBackList();
		},
		onShow: function() {
			this.getPageData();
			let args = plus.runtime.arguments;
			if (args) {
				plus.runtime.arguments = null; //进入之后就把urlscheme清空要不然下一次oushow时还会执行
				// 处理args参数，如直达到某新页面等
				//通过code请求获取user_id
				var authCode = args.split("=")[1];
				if (authCode != undefined && authCode != "" && authCode != null) {
					const obj = {
						auth_code: authCode,
					}
					authorizationApi.aliLogins(obj).then(res => {
						console.log(res, 'res');
					}).catch(err => {
						console.log(err, 'err');
					})
				}
			}
		},
		methods: {
			// 跳转转账页面
			pushPage(url){
				uni.navigateTo({
					url
				})
			},
			// 滑动打开事件
			open(index) {
				this.slideIndex = index;
				this.bankCardList.filter(item => item.id === index)[0].show = true;
				this.bankCardList.filter(item => item.id !== index).forEach(value => {
					value.show = false
				})
			},
			// 选择银行卡
			selectCard(id) {
				this.currentIndex = id;
			},
			// 操作滑动项
			setSetting(index, index1) {
				if (index1 === 0) {
					const editInfo = this.bankCardList.filter(item => item.id === this.slideIndex)[0];
					this.form = {
						account: editInfo.account,
						real_name: editInfo.nickname,
						bank: editInfo.name,
						subbank: editInfo.branch,
						id: this.slideIndex
					}
					this.$refs.addBankPopup.open();
				} else {
					this.cleanBankCard(this.slideIndex);
				}
			},
			// 删除银行卡
			cleanBankCard(id) {
				uni.showModal({
					title: '温馨提示',
					content: '是否删除该张银行卡?',
					success: ({
						confirm
					}) => {
						if (confirm) {
							withdrawApi.delBank({
								id
							}).then(res => {
								if (res.status === 200) {
									uni.showToast({
										title: '银行卡删除成功'
									})
									this.getBackList();
								}
							})
						}
					}
				})
			},
			// 添加银行卡
			submitAddBank() {
				const app = this;
				const obj = {
					name: app.form.bank,
					branch: app.form.subbank,
					nickname: app.form.real_name,
					account: app.form.account,
					id: app.form.id || '',
					type: 1
				}
				withdrawApi.addBank(obj).then(res => {
					if (res.status === 200) {
						uni.showToast({
							title: '银行卡添加成功',
							// title: `银行卡${obj.id ? '修改' : '添加'}成功`,
							duration: 2000,
							success: function() {
								app.getBackList();
								app.form = {};
								app.$refs.addBankPopup.close();
							}
						})
					}
				})
			},
			// 点击打开添加弹窗
			openAddBank() {
				this.$refs.addBankPopup.open();
			},
			// 获取银行卡列表
			getBackList() {
				const app = this;
				withdrawApi.getBackList().then(res => {
					app.bankCardList = res.data.list.map(item => {
						item.show = false;
						return item
					});
					console.log(app.bankCardList, 'app.bankCardList');
				})
			},
			// 提现记录
			viewRecord() {
				this.$navTo('pages/wallet/withdrawCash/log');
			},
			// 奖励记录
			toBalanceLog() {
				this.$navTo('pages/wallet/withdrawCash/balanceLog');
			},
			onSubmit(){
				if(!this.password)return this.$toast('请输入密码！')
				const app = this;
				// const bankInfo = app.bankCardList.filter(item => item.id === app.currentIndex)[0];
				// if (app.validteWithdrawReceived(String(app.withdrawReceived))) {
				// 	withdrawApi.withdrawApply({
				// 			money: app.withdrawReceived,
				// 			type: 2,
				// 			real_name: bankInfo.nickname,
				// 			account: bankInfo.account,
				// 			bank: bankInfo.name,
				// 			subbank: bankInfo.branch,
				// 			remark: '',
				// 			pay_password:app.password
				// 		})
				// 		.then(res =>{
				// 			 this.$success('提现成功!')
				// 			 this.showPassword = false
				// 		})
				// 		.catch(res => this.$error(res))
				// }
				
				
				
				
				withdrawApi.withdrawApply({
					type:3,
					real_name:this.withdrawReceived>=2000?this.real_name:undefined,
					pay_password:app.password,
					money: app.withdrawReceived,
					}).then(res =>{
							 this.$success('提现成功!')
							 this.showPassword = false
						})
				
			},
			// 提现
			toWithdrawApply() {
				if(!this.withdrawReceived) return this.$error('请输入提现金额1')
				if(this.withdrawReceived>=2000 && !this.real_name)return this.$error('请输入真实姓名！')
				// if(this.currentIndex === 0) return this.$error('请选择银行卡')
				this.showPassword = true
				
			},

			// 验证提现金额
			validteWithdrawReceived(str) {
				if (Verify.isEmpty(str)) {
					this.$toast('请先输入提现金额')
					return false
				}
				return true
			},
			setDecimalPoint(str) {
				if (String(str).indexOf(".") !== -1) {
					return String(str).substr(0, String(str).indexOf(".") + 3)
				} else {
					return `${str}.00`
				}
			},
			// 点击返回上一页
			goBack() {
				uni.navigateBack(1);
			},
			// // 点击授权支付宝
			// authorizationAlipay() {
			// 	authorizationApi.authorization()
			// 		.then(result => {
			// 			this.authoriztion(result.data.appid, 'http://a.youliaoshenghuo.com/h5');
			// 		})
			// },
			// 点击授权微信
			authorizationWxpay() {
				const app = this;
				uni.login({
					provider: 'weixin', //使用微信登录
					onlyAuthorize: true,
					success: function(loginRes) {
						authorizationApi.wxLogins({
								code: loginRes.code
							})
							.then(res => {
								app.$success('微信授权绑定成功!');
							})
					},
					fail(err) {
						app.$error(err);
					}
				});
			},
			authoriztion(appID, redirectUrl) {
				let urls =
					`https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=${appID}&scope=auth_user&redirect_uri=${redirectUrl}`;
				urls = encodeURIComponent(urls); //将地址编码成浏览器访问的格式
				// 判断平台
				if (plus.os.name == 'Android') {
					plus.runtime.openURL(
						'alipays://platformapi/startapp?appId=20000067&url=' + urls,
						res => {
							//这里写打开URL地址失败后的处理
							uni.showModal({
								content: '本机未检测到对应客户端，是否打开浏览器访问页面？',
								success: function(res) {
									if (res.confirm) {
										plus.runtime.openURL();
									}
								}
							});
						},
						'com.eg.android.AlipayGphone'
					);
				} else if (plus.os.name == 'iOS') {
					plus.runtime.openURL(
						'alipay://platformapi/startapp?appId=20000067&url=' + urls,
						res => {
							console.log(res);
							uni.showModal({
								content: '本机未检测到对应客户端，是否打开浏览器访问页面？',
								success: function(res) {
									if (res.confirm) {
										//plus.runtime.openURL(url);
									}
								}
							});
						},
						'com.eg.android.AlipayGphone'
					);
				}
			},
			// 获取页面数据
			getPageData() {
				const app = this
				app.isLoading = true
				Promise.all(app.getUserInfo())
					.then(() => app.isLoading = false)
			},
			// 获取会员信息
			getUserInfo() {
				const app = this
				return new Promise((resolve, reject) => {
					UserApi.info()
						.then(result => {
							console.log(result.data.userInfo, 'result');
							app.userInfo = result.data.userInfo
							resolve(app.userInfo)
						})
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.withdraw-cash-box {
		height: 100%;
		padding-top: 10%;
		background: linear-gradient(to right, #ffecd0, #fff5e7);

		.withdraw-cash-navbar {
			position: relative;
			text-align: center;
			font-size: 18px;
			color: #c59a46;
			padding: 12px 16px;

			.to-back {
				width: 36rpx;
				height: 36rpx;
				position: absolute;
				left: 10px;
				top: 50%;
				transform: translateY(-50%);
			}
			.to-right {
				// width: 36rpx;
				// height: 36rpx;
				position: absolute;
				right: 10px;
				top: 50%;
				transform: translateY(-50%);
			}
		}

		.withdraw-cash-remarks {
			padding: 18px 16px;
			background: rgba(255, 255, 255, .3);

			.withdraw-cash-remarks-title {
				color: #c59a46;
			}
		}

		.balance-box {
			text-align: center;
			color: #c59a46;
			padding: 20px 0;

			.my-balance-head {
				font-size: 12px;
				margin-bottom: 6px;
			}

			.my-balance-body {
				font-size: 26px;
			}
		}

		.withdraw-cash-content {
			background-color: #fff;
			border-radius: 12px 12px 0 0;
			padding: 0 12px;

			.amount-withdrawn {
				font-size: 18px;
				font-weight: 550;
				padding: 16px 0;
				margin-bottom: 20px;

				.amount-withdrawn-input {
					border-radius: 12px;
					background-color: #ededed;
					padding: 10px;
					margin-top: 12px;
				}

				.amount-withdrawn-title {
					margin-top: 20rpx;
					margin-left: 10rpx;
					font-size: 12px;
					color: #b5b5b5;
				}
			}

			.alipay-box {
				position: relative;
				display: flex;
				align-items: center;
				padding: 12px 0 12px 10px;
				border-radius: 12px;
				color: #c59a46;
				margin-bottom: 8px;

				.alipay-logo {
					width: 180px;
				}

				.alipay-icon {
					width: 32rpx;
					height: 32rpx;
					position: absolute;
					right: 10px;
					top: 50%;
					transform: translateY(-50%);
				}
			}

			.bank-card {

				.card-box {
					height: 200px;
					overflow: auto;

					.item {
						display: flex;
						justify-content: space-between;
						align-items: center;
						padding: 20rpx;
					}

					.card-list {
						background: linear-gradient(to right, #f8edd6, #fbf7ef);
						border-radius: 20rpx;
						overflow: hidden;
						border: 1px solid #c59a46;
						color: #c59a46;
						// display: flex;
						// justify-content: space-between;
						// align-items: center;
						margin-bottom: 30rpx;
					}
				}
			}

			.add-card {
				width: 100%;
				padding: 10rpx 0;
				background-color: #ededed;
				border-radius: 20rpx;
				border: 1px dashed #c59a46;
				color: #c59a46;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-top: 30rpx;
			}

			.withdraw-cash-tip {
				font-size: 12px;
				color: #b5b5b5;
			}

			.immediate-withdrawal {
				margin: 30px 20px 0 20px;
				padding: 12px 20px;
				text-align: center;
				border-radius: 25px;
				background: linear-gradient(to right, #f8edd6, #fbf7ef);

				.immediate-withdrawal-title {
					color: #c59a46;
				}
			}

			.foot-record {
				margin-top: 20%;
				padding-bottom: 30rpx;
				display: flex;
				justify-content: space-around;

				.withdraw-cash-record {}

				.reward-record {}
			}
		}

		.withdraw-alipay {
			padding: 40rpx;
			border-radius: 20rpx;
			background-color: #fff;
		}

		.submit-btn {
			padding: 8px 0;
			margin-top: 20rpx;
			border-radius: 25px;
			text-align: center;
			color: #c59a46;
			background: linear-gradient(to right, #f8edd6, #fbf7ef);
		}
	}
	.password_box{
		.title{
			font-size: 36rpx;
			font-weight: 600;
			text-align: center;
			margin: 30rpx 0;
		}
		.input{
			width: 80%;
			margin:0 auto;
			margin-bottom: 30rpx;
		}
		.button{
			width: 500rpx;
			height: 70rpx;
			background-color: rgb(255, 44, 59);
			border-radius: 25rpx;
			margin: 30rpx auto;
			text-align: center;
			color: white;
			line-height: 70rpx;
		}
	}
</style>